// WebSocket客户端类
class WebSocketClient {
  constructor() {
    this.ws = null;
    this.url = '';
    this.connected = false;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.reconnectInterval = 3000;
    this.reconnectTimer = null;
    this.messageHandlers = [];
    this.connectionChangeHandlers = [];
  }

  connect(url) {
    return new Promise((resolve, reject) => {
      try {
        this.url = url;
        this.ws = new WebSocket(url);

        this.ws.onopen = () => {
          console.log('WebSocket连接已建立');
          this.connected = true;
          this.reconnectAttempts = 0;
          this.notifyConnectionChange(true);
          
          // 发送连接消息
          this.send({
            type: 'connect',
            clientId: this.generateClientId(),
            timestamp: Date.now()
          });

          resolve();
        };

        this.ws.onmessage = (event) => {
          try {
            const data = JSON.parse(event.data);
            this.handleMessage(data);
          } catch (error) {
            console.error('解析消息失败:', error);
          }
        };

        this.ws.onerror = (error) => {
          console.error('WebSocket错误:', error);
          reject(error);
        };

        this.ws.onclose = () => {
          console.log('WebSocket连接已关闭');
          this.connected = false;
          this.notifyConnectionChange(false);
          this.attemptReconnect();
        };

      } catch (error) {
        reject(error);
      }
    });
  }

  disconnect() {
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
      this.reconnectTimer = null;
    }

    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }

    this.connected = false;
    this.reconnectAttempts = 0;
  }

  send(message) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(message));
      return true;
    }
    return false;
  }

  attemptReconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.log('达到最大重连次数');
      this.notifyConnectionChange(false, '连接失败，请检查网络或重新输入服务器地址');
      return;
    }

    this.reconnectAttempts++;
    console.log(`尝试重新连接 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
    this.notifyConnectionChange(false, '正在重新连接...', true);

    this.reconnectTimer = setTimeout(() => {
      this.connect(this.url).catch(error => {
        console.error('重连失败:', error);
      });
    }, this.reconnectInterval);
  }

  handleMessage(data) {
    this.messageHandlers.forEach(handler => handler(data));
  }

  onMessage(callback) {
    this.messageHandlers.push(callback);
  }

  onConnectionChange(callback) {
    this.connectionChangeHandlers.push(callback);
  }

  notifyConnectionChange(connected, message = '', reconnecting = false) {
    this.connectionChangeHandlers.forEach(handler => 
      handler(connected, message, reconnecting)
    );
  }

  generateClientId() {
    return 'client_' + Math.random().toString(36).substr(2, 9);
  }

  isConnected() {
    return this.connected && this.ws && this.ws.readyState === WebSocket.OPEN;
  }
}

// UI控制器类
class UIController {
  constructor() {
    this.statusIndicator = document.getElementById('statusIndicator');
    this.statusText = this.statusIndicator.querySelector('.status-text');
    this.prevBtn = document.getElementById('prevBtn');
    this.nextBtn = document.getElementById('nextBtn');
    this.notification = document.getElementById('notification');
    this.buttonsDisabled = false;
  }

  updateConnectionStatus(connected, reconnecting = false) {
    if (connected) {
      this.statusIndicator.classList.add('connected');
      this.statusIndicator.classList.remove('connecting');
      this.statusText.textContent = '已连接';
    } else if (reconnecting) {
      this.statusIndicator.classList.remove('connected');
      this.statusIndicator.classList.add('connecting');
      this.statusText.textContent = '重新连接中...';
    } else {
      this.statusIndicator.classList.remove('connected', 'connecting');
      this.statusText.textContent = '未连接';
    }
  }

  disableButtons(duration) {
    if (this.buttonsDisabled) return;

    this.buttonsDisabled = true;
    this.prevBtn.disabled = true;
    this.nextBtn.disabled = true;

    setTimeout(() => {
      this.buttonsDisabled = false;
      this.prevBtn.disabled = false;
      this.nextBtn.disabled = false;
    }, duration);
  }

  showNotification(message, type = 'info', duration = 3000) {
    this.notification.textContent = message;
    this.notification.className = `notification ${type} show`;

    setTimeout(() => {
      this.notification.classList.remove('show');
    }, duration);
  }

  bindButtonEvents(onPrev, onNext) {
    this.prevBtn.addEventListener('click', () => {
      if (!this.buttonsDisabled) {
        this.prevBtn.classList.add('active');
        setTimeout(() => this.prevBtn.classList.remove('active'), 50);
        onPrev();
      }
    });

    this.nextBtn.addEventListener('click', () => {
      if (!this.buttonsDisabled) {
        this.nextBtn.classList.add('active');
        setTimeout(() => this.nextBtn.classList.remove('active'), 50);
        onNext();
      }
    });
  }
}

// 幻灯片预览类
class SlidePreview {
  constructor() {
    this.previewImage = document.getElementById('previewImage');
    this.previewLoading = document.getElementById('previewLoading');
    this.slideNumber = document.getElementById('slideNumber');
    this.currentSlide = 1;
  }

  updatePreview(imageData, slideIndex) {
    const startTime = Date.now();

    this.currentSlide = slideIndex;
    this.slideNumber.textContent = `第 ${slideIndex} 页`;

    this.showLoading();

    this.previewImage.onload = () => {
      this.hideLoading();
      this.previewImage.classList.add('loaded');
      
      const loadTime = Date.now() - startTime;
      console.log(`预览图像加载完成 (耗时: ${loadTime}ms)`);

      if (loadTime > 200) {
        console.warn(`警告: 图像加载时间超过200ms (${loadTime}ms)`);
      }
    };

    this.previewImage.onerror = () => {
      console.error('预览图像加载失败');
      this.hideLoading();
      this.showError();
    };

    this.previewImage.src = imageData;
  }

  showLoading() {
    this.previewLoading.style.display = 'block';
  }

  hideLoading() {
    this.previewLoading.style.display = 'none';
  }

  showError() {
    this.previewLoading.textContent = '加载失败';
    this.previewLoading.style.display = 'block';
  }

  getCurrentSlide() {
    return this.currentSlide;
  }
}

// 提示词管理类
class NotesManager {
  constructor() {
    this.notesTextarea = document.getElementById('notesTextarea');
    this.currentSlide = 1;
    this.autoSaveTimer = null;
    this.autoSaveDelay = 1000;
    this.storageKey = 'ppt_notes';
    
    this.bindEvents();
  }

  bindEvents() {
    this.notesTextarea.addEventListener('input', () => {
      this.autoSave();
    });
  }

  loadNotes(slideIndex) {
    this.currentSlide = slideIndex;
    const allNotes = this.getAllNotes();
    const notes = allNotes[slideIndex] || '';
    this.notesTextarea.value = notes;
  }

  saveNotes(slideIndex, content) {
    try {
      const allNotes = this.getAllNotes();
      allNotes[slideIndex] = content;
      localStorage.setItem(this.storageKey, JSON.stringify(allNotes));
      return true;
    } catch (error) {
      console.error('保存提示词失败:', error);
      return false;
    }
  }

  autoSave() {
    if (this.autoSaveTimer) {
      clearTimeout(this.autoSaveTimer);
    }

    this.autoSaveTimer = setTimeout(() => {
      const content = this.notesTextarea.value;
      this.saveNotes(this.currentSlide, content);
      console.log(`提示词已自动保存 (页码: ${this.currentSlide})`);
    }, this.autoSaveDelay);
  }

  getAllNotes() {
    try {
      const data = localStorage.getItem(this.storageKey);
      return data ? JSON.parse(data) : {};
    } catch (error) {
      console.error('读取提示词失败:', error);
      return {};
    }
  }

  clearAllNotes() {
    localStorage.removeItem(this.storageKey);
  }
}

// 连接管理类
class ConnectionManager {
  constructor() {
    this.serverAddress = document.getElementById('serverAddress');
    this.connectBtn = document.getElementById('connectBtn');
    this.scanBtn = document.getElementById('scanBtn');
    this.storageKey = 'last_server_url';
    
    this.loadLastServer();
  }

  bindEvents(onConnect, onScan) {
    this.connectBtn.addEventListener('click', () => {
      const address = this.serverAddress.value.trim();
      if (address) {
        onConnect(address);
      }
    });

    this.scanBtn.addEventListener('click', () => {
      onScan();
    });

    this.serverAddress.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        this.connectBtn.click();
      }
    });
  }

  getServerUrl(address) {
    // 如果没有协议前缀，添加ws://
    if (!address.startsWith('ws://') && !address.startsWith('wss://')) {
      address = 'ws://' + address;
    }
    return address;
  }

  saveLastServer(address) {
    try {
      localStorage.setItem(this.storageKey, address);
    } catch (error) {
      console.error('保存服务器地址失败:', error);
    }
  }

  loadLastServer() {
    try {
      const lastServer = localStorage.getItem(this.storageKey);
      if (lastServer) {
        // 移除ws://前缀显示
        const displayAddress = lastServer.replace(/^wss?:\/\//, '');
        this.serverAddress.value = displayAddress;
      }
    } catch (error) {
      console.error('加载服务器地址失败:', error);
    }
  }

  validateAddress(address) {
    // 简单验证IP:端口格式
    const pattern = /^(\d{1,3}\.){3}\d{1,3}:\d+$/;
    return pattern.test(address) || address.includes('localhost');
  }
}

// 二维码扫描器类
class QRScanner {
  constructor() {
    this.qrScanner = document.getElementById('qrScanner');
    this.closeScanBtn = document.getElementById('closeScanBtn');
    this.qrReader = document.getElementById('qrReader');
    this.html5QrCode = null;
  }

  bindEvents(onClose) {
    this.closeScanBtn.addEventListener('click', () => {
      this.stopScan();
      onClose();
    });
  }

  async startScan(onSuccess) {
    this.qrScanner.classList.remove('hidden');

    try {
      // 动态加载html5-qrcode库
      if (typeof Html5Qrcode === 'undefined') {
        await this.loadQRCodeLibrary();
      }

      this.html5QrCode = new Html5Qrcode("qrReader");
      
      await this.html5QrCode.start(
        { facingMode: "environment" },
        {
          fps: 10,
          qrbox: { width: 250, height: 250 }
        },
        (decodedText) => {
          console.log('二维码扫描成功:', decodedText);
          this.stopScan();
          onSuccess(decodedText);
        },
        (errorMessage) => {
          // 扫描错误（正常情况）
        }
      );

    } catch (error) {
      console.error('启动二维码扫描失败:', error);
      alert('无法启动摄像头，请检查权限设置');
      this.stopScan();
    }
  }

  stopScan() {
    if (this.html5QrCode) {
      this.html5QrCode.stop().catch(err => console.error('停止扫描失败:', err));
      this.html5QrCode = null;
    }
    this.qrScanner.classList.add('hidden');
  }

  async loadQRCodeLibrary() {
    return new Promise((resolve, reject) => {
      const script = document.createElement('script');
      script.src = 'https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js';
      script.onload = resolve;
      script.onerror = reject;
      document.head.appendChild(script);
    });
  }
}

// 主应用类
class PPTRemoteApp {
  constructor() {
    this.wsClient = new WebSocketClient();
    this.uiController = new UIController();
    this.slidePreview = new SlidePreview();
    this.notesManager = new NotesManager();
    this.connectionManager = new ConnectionManager();
    this.qrScanner = new QRScanner();
    
    this.init();
  }

  init() {
    // 绑定WebSocket事件
    this.wsClient.onMessage((data) => this.handleServerMessage(data));
    this.wsClient.onConnectionChange((connected, message, reconnecting) => {
      this.uiController.updateConnectionStatus(connected, reconnecting);
      
      if (message) {
        const type = connected ? 'success' : 'error';
        this.uiController.showNotification(message, type);
      }
    });

    // 绑定UI事件
    this.uiController.bindButtonEvents(
      () => this.sendControlCommand('previous'),
      () => this.sendControlCommand('next')
    );

    // 绑定连接事件
    this.connectionManager.bindEvents(
      (address) => this.handleConnect(address),
      () => this.handleScan()
    );

    // 绑定二维码扫描事件
    this.qrScanner.bindEvents(() => {
      // 关闭扫描器
    });

    console.log('PPT远程控制器已初始化');
  }

  async handleConnect(address) {
    if (!this.connectionManager.validateAddress(address)) {
      this.uiController.showNotification('请输入有效的服务器地址 (例: 192.168.0.102:7663)', 'error');
      return;
    }

    const url = this.connectionManager.getServerUrl(address);
    
    try {
      this.uiController.showNotification('正在连接...', 'info');
      await this.wsClient.connect(url);
      this.connectionManager.saveLastServer(address);
      this.uiController.showNotification('连接成功！', 'success');
    } catch (error) {
      console.error('连接失败:', error);
      this.uiController.showNotification('无法连接到服务器，请检查IP地址和端口', 'error');
    }
  }

  handleScan() {
    this.qrScanner.startScan((url) => {
      // 从URL中提取地址
      const address = url.replace(/^https?:\/\//, '');
      this.connectionManager.serverAddress.value = address;
      this.handleConnect(address);
    });
  }

  sendControlCommand(action) {
    if (!this.wsClient.isConnected()) {
      this.uiController.showNotification('未连接到服务器', 'error');
      return;
    }

    const startTime = Date.now();

    const success = this.wsClient.send({
      type: 'control',
      action: action,
      timestamp: startTime
    });

    if (success) {
      this.uiController.disableButtons(200);
      
      const sendTime = Date.now() - startTime;
      console.log(`控制指令已发送: ${action} (耗时: ${sendTime}ms)`);

      if (sendTime > 100) {
        console.warn(`警告: 发送时间超过100ms (${sendTime}ms)`);
      }
    } else {
      this.uiController.showNotification('发送指令失败', 'error');
    }
  }

  handleServerMessage(data) {
    const { type } = data;

    switch (type) {
      case 'connected':
        console.log('服务器连接确认:', data);
        if (data.currentSlide) {
          this.notesManager.loadNotes(data.currentSlide);
        }
        break;

      case 'slideUpdate':
        console.log('收到幻灯片更新:', data.slideIndex);
        this.slidePreview.updatePreview(data.imageData, data.slideIndex);
        this.notesManager.loadNotes(data.slideIndex);
        break;

      case 'error':
        console.error('服务器错误:', data.message);
        this.uiController.showNotification(data.message, 'error');
        break;

      case 'notification':
        this.uiController.showNotification(data.message, 'info');
        break;

      default:
        console.log('未知消息类型:', type);
    }
  }
}

// 启动应用
document.addEventListener('DOMContentLoaded', () => {
  window.app = new PPTRemoteApp();
});
